package com.yonyou.brigade.third_parties.ctrip.bigcustomer.util;

import com.yonyou.brigade.third_parties.ctrip.bigcustomer.config.CtripBigCustomerConstants;
import com.yonyou.brigade.third_parties.ctrip.model.CtripConfig;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.lang.CharEncoding;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by mazhqc on 2016/7/07.
 */
public class CtripBigCustomerRMIUtils {
    private static Logger logger = LoggerFactory.getLogger(CtripBigCustomerRMIUtils.class);

    public static String ssoMobileLogin(String employeeId, CtripConfig ctripConfig, String initPage, int tokenType, HttpServletResponse
            response) throws IOException {
        // Ticket 获取 URL
        String appKey= ctripConfig.getAppKey();
        String appSecurity=ctripConfig.getAppSecurity();
        //Json 串
        String ticketPostString =
                "{\"appKey\":\""+appKey+"\",\"appSecurity\":\""+appSecurity+"\", \"TokenType\":"+tokenType+", \"GroupID\":2909}";
       logger.info("ticket params:"+ticketPostString);
        //POST
        String ticketResponse = sendPost(CtripBigCustomerConstants.LOGIN_TICKET_URL, ticketPostString);
        //构造 JSON 对象,需要导入 net.sf.json 包
        JSONObject jsonObject = (JSONObject)
                JSONSerializer.toJSON(ticketResponse);
        if(!jsonObject.optBoolean("Success")){
            logger.error("Cannot call ctrip RMI: "+jsonObject.optString("Message"));
            throw new RuntimeException("Cannot call ctrip RMI: "+jsonObject.optString("Message"));
        }
        //获取 Ticket
        String token=(String)jsonObject.get("Token");
        String responseText = "<html>\n" +
                "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" >\n" +
                "<script type=\"text/javascript\">function formSubmit(){document.getElementById(\"fLogin\").submit();}</script>\n"+
                "</head>\n" +
                "<body>\n" +
                "<form name=\"fLogin\" id=\"fLogin\" action=\"http://ct.ctrip.com/m/SingleSignOn/H5SignInfo\" method=\"post\">\n" +
                "<input type=\"hidden\" name=\"accessuserid\" value=\""+appKey+"\" />\n" +
                "<input type=\"hidden\" name=\"employeeid\" value=\""+employeeId+"\" />\n" +
                "<input type=\"hidden\" name=\"initpage\" value=\""+initPage+"\"/>\n" +
                "<input type=\"hidden\" name=\"appid\" value=\""+ctripConfig.getCorporationId()+"\" />\n" +
                "<input type=\"hidden\" name=\"endorsementID\" value=\"\" />\n" +
                "<input type=\"hidden\" name=\"token\" value=\""+token+"\"/>\n" +
                "<input type=\"hidden\" name=\"channel\" value=\"\"/>\n" +
                "<input type=\"hidden\" name=\"OnError\" value=\"ErrorCode\"/>\n"+
                "<script language=\"javascript\">formSubmit();</script>\n" +
                "</form>\n" +
                "</body>\n" +
                "</html>";
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.println(responseText);
        return responseText;
    }

    public static String doRMIOrdersSearch(String startDate, String endDate, CtripConfig ctripConfig){
        String orderResults;
        try {
            String params = "{\"appKey\":\"" + ctripConfig.getAppKey() + "\",\"appSecurity\":\"" + ctripConfig.getAppSecurity() + "\"}";
            String ticketResponse = sendPost(CtripBigCustomerConstants.ORDER_TICKET_URL, params);
            //构造 JSON 对象,需要导入 net.sf.json 包
            JSONObject jsonObject = (JSONObject)
                    JSONSerializer.toJSON(ticketResponse);
            JSONObject statusObject = jsonObject.optJSONObject("Status");
            if (!statusObject.optBoolean("Success")) {
                logger.error("Cannot call ctrip RMI: " + statusObject.optString("Message"));
                throw new RuntimeException("Cannot call ctrip RMI: " + jsonObject.optString("Message"));
            }
            String ticket = jsonObject.optString("Ticket");//"+Thread.currentThread().getName()+"
            String postString = "{\"request\": {\"Auth\": {\"AppKey\": \"" + ctripConfig.getAppKey() + "\", \"Ticket\":\"" + ticket + "\"},\"JourneyNo\": \"\",\"OrderID\":\"\",\"EID\":\"\",\"DateFrom\": \""
                    + startDate + "\",\"DateTo\": \"" + endDate + "\",\"SearchType\": \"1\",\"Version\": \"\"}}";
            logger.info("获取携程订单:"+postString);
            orderResults = sendPost(CtripBigCustomerConstants.ORDER_URL, postString);
            logger.info("获取携程订单结果："+orderResults);
            return orderResults;
        }catch (Exception e){
            logger.error("获取携程订单失败！", e);
            return null;
        }

    }
    //Post method
    public static String sendPost(String url, String param) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) realUrl.openConnection();// 打开和 URL 之间的连接
            // 发送 POST 请求必须设置如下两行
            conn.setRequestMethod("POST"); // POST 方法
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.connect();
            out = new OutputStreamWriter(conn.getOutputStream(), CharEncoding.UTF_8);// 获取 URLConnection 对象对应的输出流
            out.write(param);// 发送请求参数
            out.flush();// flush 输出流的缓冲
            in = new BufferedReader(new
                    InputStreamReader(conn.getInputStream(), CharEncoding.UTF_8));//定义 BufferedReader 输入流来读取 URL的响应
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
                System.out.println("OK");
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！ "+e);
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            throw new RuntimeException("向携程发送 POST 请求出现异常！", e);
        }
        //使用 finally 块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
}
